import { store } from "@/stores";
import { fetchEntitytype, fetchEntitytyperel } from "@/api/associationAnalysis";
import { defineStore } from "pinia";
import type { KBState } from "./helper";
import {
  defaultSetting,
  getLocalState,
  removeLocalState,
  setLocalState,
} from "./helper";

export const useKBStore = defineStore("KB-storage", {
  state: (): KBState => getLocalState(),
  getters: {
    getTagEdgesByName(state) {
      return (code) => {
        const tagEdge = state.tagEdges.find((item) => item.code === code) ?? {
          name: code,
        };
        return tagEdge.name;
      };
    },
  },
  actions: {
    updateKB(KB: Partial<KBState>) {
      this.$state = { ...this.$state, ...KB };
      this.recordState();
    },

    async fetchTags() {
      const { data } = await fetchEntitytype();
      this.updateKB({ tags: data.records });
    },

    async fetchTyperel() {
      const { data } = await fetchEntitytyperel();
      this.updateKB({ tagEdges: data.records });
    },

    resetDrawer() {
      this.$state = defaultSetting();
      removeLocalState();
    },

    recordState() {
      setLocalState(this.$state);
    },
  },
});

export function useKBStoreHook() {
  return useKBStore(store);
}
